package telbook;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name=request.getParameter("username");
		String password=request.getParameter("password");
		String role=request.getParameter("role");
		Cookie cookie=new Cookie("role", role);
		response.addCookie(cookie);
		UserBean userbean=new UserBean();
		userbean.setName(name);
		Connection conn=null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
//			获取数据连接
			conn=JDBCUtils.getConnection();
//			获取Statement对象
			stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
//			发送SQL语句
			String sql="select password from "+role+" where name='"+name+"'";
			rs=stmt.executeQuery(sql);
			if(rs.next()) {
				rs.previous();
				while(rs.next()) {
					String dpassword=rs.getString("password");
					if(dpassword.equals(password)) {
						cookie=new Cookie("userbean", name);
						response.addCookie(cookie);
						if(role.equals("users"))
							response.sendRedirect(request.getContextPath()+"/index.jsp");
						else
							response.sendRedirect(request.getContextPath()+"/index2.jsp");

						
					}
					else {
						request.setAttribute("errorMsg", "密码错误");
						request.getRequestDispatcher("/loginin.jsp")
						.forward(request, response);
					}
				}
				
			}
			else {
				request.setAttribute("errorMsg1", "账号不存在");
				request.getRequestDispatcher("/loginin.jsp")
				.forward(request, response);
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.release(rs, stmt, conn);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
